const bluetooth = requirePlugin("hello-plugin")
const util = require("./utils/util");
const {
  handleToast,
  handleAlert,
  closeToast
} = require("./utils/alertUtil"); /**提示框工具类*/
const globalData_ = requirePlugin("hello-plugin")
// app.js
App({

  /**
   * 全局变量声明
   */
  globalData: {
    userInfo: null,
    /** 用户信息 */
    isConnectedBluetooth: false,
    /** 是否连接蓝牙 */
    BDevName: "",
    devcieInfo: null,
    supportOTA: false, // 是否开启杰理OTA
    isJlAutned: false, // 判断是否已认证
    isOTA: false,
    isSearch: false
  },

  onLaunch() {
    // 设置过滤产品类型（屏蔽） 不区分大小写 --> 屏蔽戒指：ring 屏蔽手表：watch 
    bluetooth.setSdkStorageValue("filterProductType","null")

    // 监听系统蓝牙开关
    bluetooth.onBluetoothAdapterStateChange((res)=>{
      if (res.available) {
        if (!this.globalData.isSearch && !this.globalData.isOTA) {
          bluetooth.initBluetooth((res)=>{
            connectBack()
          })
        }
      } else {
        console.log("蓝牙关闭");
      }
    })

    bluetooth.onBLEConnectionStateChange((res) => {
      console.log("监听到蓝牙状态发生改变：", res);
      if (!res.connected) {
        handleToast("蓝牙已断开", "warning", 3.5)
        this.globalData.isConnectedBluetooth = false;
        this.globalData.isJlAutned = false;
        this.globalData.deviceId = ""
        this.globalData.devcieInfo = null
        this.globalData.BDevName = ""
        if (!this.globalData.isOTA && !this.globalData.isSearch) {
          wx.reLaunch({
            url: '/pages/index/index',
          })
          bluetooth.initBluetooth((res)=>{
            connectBack()
          })
        }
      }
    });
    bluetooth.initBluetooth(function (res) {
      connectBack()
    })

    // 80天登录一次，刷新token
    const expirationToken  = wx.getStorageSync('expirationToken') ||  (Date.now() - 24 * 60 * 60 * 1000);
    console.log("缓存时间戳：" + expirationToken);  
    if(Date.now() > expirationToken){
      console.log("缓存过期重新登录");
        wx.login({
          success: (res) => {
            console.log("login:", JSON.stringify(res));
            console.log(res.code);
            if (res.code) {
              util.wxLogin(res.code, (res) => {
                // 登录成功会返回用户信息，包含token
                console.log("wxLogin:", JSON.stringify(res.data));
                if (typeof res.data === 'object') {
                  const responseData = res.data;
                  console.log("login", responseData.data) //res.data中有openid
                  // 缓存用户信息
                  this.globalData.userInfo = responseData.data
                  wx.setStorageSync('user', responseData.data)
                  // 计算80天后的时间戳(服务器为90天)
                  const expirationTime = Date.now() + 80 * 24 * 60 * 60 * 1000; 
                  // token 过期时间
                  wx.setStorageSync('expirationToken', expirationTime)
                }
    
              })
            }
    
          }
        })
    }

    function connectBack(){
      const that = this
      const deviceId = wx.getStorageSync('deviceId') || null
      console.error("回连设备中..." + deviceId);
      if (deviceId) {
        handleToast("回连设备中...", "loading", 100)

        bluetooth.connectDevice(deviceId,(state,res) => {
          closeToast()
          if (state) {
            console.warn("回连成功");
            const app = getApp()
            const oldDeviceName = wx.getStorageSync('deviceName') || null
            app.globalData.deviceId = deviceId
            app.globalData.isConnectedBluetooth = true
            if (oldDeviceName != null) {
              app.globalData.BDevName = oldDeviceName
            }
          }
        })
      }
    }

  },

})